import React,{ useEffect, useState } from 'react';
import { Row, Col ,Input, Select ,Button ,DatePicker, message } from 'antd'
import '../styles/AddArticle.css'
import marked from 'marked'
import axios from 'axios'
import servicePath from '../config/baseUrl'
const { Option } = Select;
const { TextArea } = Input

const AddArticle = (props) => {
  const [articleId,setArticleId] = useState(0)  // 文章的ID，如果是0说明是新增加，如果不是0，说明是修改
  const [articleTitle,setArticleTitle] = useState('')   //文章标题
  const [articleContent , setArticleContent] = useState('')  //markdown的编辑内容
  const [markdownContent, setMarkdownContent] = useState('预览内容') //html内容
  const [introducemd,setIntroducemd] = useState()            //简介的markdown内容
  const [introducehtml,setIntroducehtml] = useState('等待编辑') //简介的html内容
  const [showDate,setShowDate] = useState()   //发布日期
  const [updateDate,setUpdateDate] = useState() //修改日志的日期
  const [typeInfo ,setTypeInfo] = useState([]) // 文章类别信息
  const [selectedType,setSelectType] = useState('') //选择的文章类别

  useEffect(() => {
    getTypeInfo() // 获得文章分类信息
    let tmpId = props.match.params.id
    if(tmpId) {
      setArticleId(tmpId)
      getArticleById(tmpId)
    }
  }, []) // 数组空代表只执行一次

  const changeContent = (e)=>{
    setArticleContent(e.target.value)
    let html=marked(e.target.value)
    setMarkdownContent(html)
  }

  const changeIntroduce = (e)=>{
    setIntroducemd(e.target.value)
    let html=marked(e.target.value)
    setIntroducehtml(html)
  }
  
  // 从中台接口获得文章类别信息
  const getTypeInfo = () => {
    axios({
      method: 'get',
      url: servicePath.getTypeInfo,
      withCredentials: true, // 允许cookie跨域
    }).then(
      resp => {
        if(resp.data.data === '没有登录') {
          localStorage.removeItem('openId')
          props.history.push('/')
        } else {
          // 路由守卫住了直接返回登录
          setTypeInfo(resp.data.data)
        }
      }
    )
  }
  // 选择类别后的设置
  const selectTypeHandler = (value) => {
    setSelectType(value)
  }
  // 编写文章保存方法
  const saveArticle = () => {
    if(!selectedType) {
      message.error('必须选择文章类型')
      return false
    } else if(!articleTitle) {
      message.error('文章名称不能为空')
      return false
    } else if(!articleContent) {
      message.error('文章内容不能为空')
      return false
    } else if(!introducemd) {
      message.error('文章简介不能为空')
      return false
    } else if(!showDate) {
      message.error('发布日期不能为空')
      return false
    }
    let dataProps = {}
    dataProps.type_id = selectedType
    dataProps.title = articleTitle
    dataProps.article_content = articleContent
    dataProps.introduce = introducemd
    let dataText = showDate.replace('-', '/') // 把字符串转换成时间戳
    dataProps.addTime = (new Date(dataText).getTime()) / 1000
    if(articleId === 0) {
      dataProps.view_count = 0 // 添加文章
      axios({
        method: 'POST',
        url: servicePath.addArticle,
        data: dataProps,
        withCredentials: true,
      }).then(resp => {
        console.log(resp);
        setArticleId(resp.data.insertId) // 修改文章
        if(resp.data.isSuccess) {
          message.success('文章添加成功')
        } else {
          message.error('文章添加出错')
        }
      })
    } else {
      dataProps.id = articleId // 修改文章
      axios({
          method:'post',
          url:servicePath.updateArticle,
          header:{ 'Access-Control-Allow-Origin':'*' },
          data:dataProps,
          withCredentials: true
      }).then(
          res=>{
          if(res.data.isScuccess){
              message.success('文章修改成功')
          }else{
              message.error('文件修改失败');
          }
          }
      )
      }
  }

  // 点击修改按钮后获得ID并且从数据库中查询显示数据
  const getArticleById = (id) => {
    axios(servicePath.getArticleById+id, {withCredentials: true})
      .then(resp => {
        console.log(resp)
        let articleInfo = resp.data.data[0]
        setArticleTitle(articleInfo.title)
        setArticleContent(articleInfo.article_content)
        let html = marked(articleInfo.article_content)
        setMarkdownContent(html)
        setIntroducemd(articleInfo.introduce)
        let tmpInt = marked(articleInfo.introduce)
        setIntroducehtml(tmpInt)
        setShowDate(articleInfo.addTime)
        setSelectType(articleInfo.typeId)
      })
  }
  marked.setOptions({
    renderer: marked.Renderer(),
    gfm: true,
    pedantic: false,
    sanitize: false,
    tables: true,
    breaks: false,
    smartLists: true,
    smartypants: false,
  });
  return (
    <div>
      {/* 编写标题和文章内容区域 */}
      <Row gutter={5}>
        <Col span={18}>
          <Row gutter={10}>
            <Col span={20}>
              <Input
                value={articleTitle}
                placeholder="博客标题" 
                size="large"
                onChange={e => {setArticleTitle(e.target.value)}}
              />
            </Col>
            <Col span={4}>
              &nbsp;
              <Select defaultValue={selectedType} size="large" onChange={selectTypeHandler}>
                {
                  typeInfo.map((item, index) => {
                    return (
                      <Option key={index} value={item.id}>{item.typeName}</Option>
                    )
                  })
                }
              </Select>
            </Col>
          </Row>
          <br/>
            <Row gutter={10} >
              <Col span={12}>
                <TextArea 
                  className="markdown-content" 
                  rows={35}  
                  placeholder="文章内容"
                  value={articleContent} 
                  onChange={changeContent}
                  onPressEnter={changeContent}
                />
              </Col>
              <Col span={12}>
                <div
                  className="show-html"
                  dangerouslySetInnerHTML = {{__html:markdownContent}}
                >
                </div>
              </Col>
            </Row>  
          </Col>
          {/* 暂停按钮和发布按钮 */}
          <Col span={6}>
            <Row>
              <Col span={24}>
                <Button  size="large">暂存文章</Button>&nbsp;
                <Button
                  type="primary"
                  size="large"
                  onClick={saveArticle}
                >发布文章</Button>
                <br/>
              </Col>
            </Row>
          </Col>
          {/* 编写文章简介部分 */}
          <Col span={24}>
            <br/>
            <TextArea 
                rows={4} 
                placeholder="文章简介"
                value={introducemd}  
                onChange={changeIntroduce} 
                onPressEnter={changeIntroduce}
            />
            <br/><br/>
            <div
              className="introduce-html"
              dangerouslySetInnerHTML = {{__html:'文章简介：'+introducehtml}}
            ></div>
          </Col>
          {/* 编写发布时间页面 */}
          <Col span={12}>
            <div className="date-select">
              <DatePicker
                onChange={(date, dateString) => {setShowDate(dateString)}}
                placeholder="发布日期"
                size="large"  
              />
            </div>
          </Col>
      </Row>
    </div>
  )
}

export default AddArticle